// pages/create-record/create-record.js
const util = require('../../utils/util')

Page({
  data: {
    isEdit: false,
    recordId: null,
    drivers: [],
    dispatchers: [],
    formData: {
      use_date: '',
      car_type: 'daily_rent',
      car_model: '',
      driver_name: '',
      license_plate: '',
      dispatcher_id: '',
      passenger_name: '',
      start_time: '',
      end_time: '',
      mileage: '',
      base_price: '',
      work_hour_limit: '',
      km_limit: '',
      overtime_fee_per_hour: '',
      over_km_fee: '',
      parking_fee: '',
      parking_fee_included: true,
      toll_fee: '',
      toll_fee_included: true,
      accommodation_fee: '',
      accommodation_fee_included: true,
      fuel_fee: '',
      fuel_fee_included: true,
      meal_fee: '',
      meal_fee_included: true,
      car_wash_fee: '',
      car_wash_fee_included: true,
      water_fee: '',
      water_fee_included: true,
      other_fee: '',
      other_fee_included: true,
      route_description: ''
    },
    carTypes: [
      { value: 'daily_rent', text: '日租' },
      { value: 'fixed_price', text: '一口价' }
    ]
  },

  onLoad(options) {
    // 设置默认日期为今天
    const today = new Date()
    this.setData({
      'formData.use_date': util.formatDate(today)
    })

    // 如果有ID参数，则为编辑模式
    if (options.id) {
      this.setData({
        isEdit: true,
        recordId: options.id
      })
      wx.setNavigationBarTitle({
        title: '编辑用车记录'
      })
      this.loadRecord(options.id)
    } else {
      wx.setNavigationBarTitle({
        title: '创建用车记录'
      })
    }

    this.loadDrivers()
    this.loadDispatchers()
  },

  // 加载司机列表
  async loadDrivers() {
    try {
      const res = await util.request('/drivers')
      if (res.code === 200) {
        this.setData({
          drivers: res.data
        })
      }
    } catch (error) {
      console.error('获取司机列表失败:', error)
    }
  },

  // 加载调车人列表
  async loadDispatchers() {
    try {
      const res = await util.request('/dispatchers')
      if (res.code === 200) {
        this.setData({
          dispatchers: res.data
        })
      }
    } catch (error) {
      console.error('获取调车人列表失败:', error)
    }
  },

  // 加载记录详情（编辑模式）
  async loadRecord(id) {
    try {
      util.showLoading('加载中...')
      const res = await util.request(`/car-records/${id}`)
      if (res.code === 200) {
        this.setData({
          formData: { ...this.data.formData, ...res.data }
        })
      } else {
        util.showToast(res.message || '加载失败')
      }
    } catch (error) {
      console.error('加载记录失败:', error)
      util.showToast('加载失败，请重试')
    } finally {
      util.hideLoading()
    }
  },

  // 表单输入处理
  onInput(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 开关切换处理
  onSwitchChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 选择器变化处理
  onPickerChange(e) {
    const { field } = e.currentTarget.dataset
    const { value } = e.detail
    
    if (field === 'car_type') {
      this.setData({
        [`formData.${field}`]: this.data.carTypes[value].value
      })
    } else if (field === 'driver_name') {
      const selectedDriver = this.data.drivers[value]
      this.setData({
        'formData.driver_name': selectedDriver.name,
        'formData.car_model': selectedDriver.car_type,
        'formData.license_plate': selectedDriver.license_plate
      })
    } else if (field === 'dispatcher_id') {
      const selectedDispatcher = this.data.dispatchers[value]
      this.setData({
        'formData.dispatcher_id': selectedDispatcher.id
      })
    }
  },

  // 日期选择
  onDateChange(e) {
    this.setData({
      'formData.use_date': e.detail.value
    })
  },

  // 时间选择
  onTimeChange(e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },

  // 表单验证
  validateForm() {
    const { formData } = this.data
    const required = [
      'use_date', 'car_model', 'driver_name', 'license_plate',
      'dispatcher_id', 'passenger_name', 'start_time', 'end_time'
    ]

    for (let field of required) {
      if (!formData[field]) {
        const fieldNames = {
          use_date: '用车日期',
          car_model: '车型',
          driver_name: '司机姓名',
          license_plate: '车牌号',
          dispatcher_id: '调车人',
          passenger_name: '用车人',
          start_time: '开始时间',
          end_time: '结束时间'
        }
        util.showToast(`请填写${fieldNames[field]}`)
        return false
      }
    }

    // 验证时间
    if (formData.start_time >= formData.end_time) {
      util.showToast('结束时间必须大于开始时间')
      return false
    }

    return true
  },

  // 提交表单
  async submitForm() {
    if (!this.validateForm()) return

    try {
      util.showLoading(this.data.isEdit ? '更新中...' : '创建中...')
      
      const app = getApp()
      const openid = app.globalData.userInfo?.openid || 'test_openid'
      
      const submitData = {
        ...this.data.formData,
        openid: openid
      }

      let res
      if (this.data.isEdit) {
        res = await util.request(`/car-records/${this.data.recordId}`, {
          method: 'PUT',
          data: submitData
        })
      } else {
        res = await util.request('/car-records', {
          method: 'POST',
          data: submitData
        })
      }

      if (res.code === 200) {
        util.showToast(this.data.isEdit ? '更新成功' : '创建成功', 'success')
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        util.showToast(res.message || '操作失败')
      }
    } catch (error) {
      console.error('提交失败:', error)
      util.showToast('操作失败，请重试')
    } finally {
      util.hideLoading()
    }
  },

  // 重置表单
  resetForm() {
    const today = new Date()
    this.setData({
      formData: {
        use_date: util.formatDate(today),
        car_type: 'daily_rent',
        car_model: '',
        driver_name: '',
        license_plate: '',
        dispatcher_id: '',
        passenger_name: '',
        start_time: '',
        end_time: '',
        mileage: '',
        base_price: '',
        work_hour_limit: '',
        km_limit: '',
        overtime_fee_per_hour: '',
        over_km_fee: '',
        parking_fee: '',
        parking_fee_included: true,
        toll_fee: '',
        toll_fee_included: true,
        accommodation_fee: '',
        accommodation_fee_included: true,
        fuel_fee: '',
        fuel_fee_included: true,
        meal_fee: '',
        meal_fee_included: true,
        car_wash_fee: '',
        car_wash_fee_included: true,
        water_fee: '',
        water_fee_included: true,
        other_fee: '',
        other_fee_included: true,
        route_description: ''
      }
    })
  }
})